package com.pai4j.ugc.controller;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.common.constants.ResourceBehaviorConstants;
import com.pai4j.common.helper.SessionHelper;
import com.pai4j.domain.vo.request.request.act.ResourceBehaviorRequestVO;
import com.pai4j.remote.act.IResourceBehaviorClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 社区共建交互控制器
 * 处理共建的点赞、收藏等交互功能
 *
 * @author: CYM-pai
 * @date: 2025/08/05 12:00
 **/
@Slf4j
@RestController
@RequestMapping("/ugc-service/community/contribution/interaction")
public class CommunityContributionInteractionController {

    @Autowired
    private IResourceBehaviorClient resourceBehaviorClient;

    /**
     * 共建点赞
     *
     * @param contributionId 共建ID
     * @return 点赞结果
     */
    @PostMapping("/like/{contributionId}")
    public PAIResponseBean<Long> likeContribution(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            
            // 构建点赞请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 调用互动服务进行点赞
            PAIResponseBean<Long> response = resourceBehaviorClient.behavior(request);
            
            if (PAIResponseBeanUtil.isOk(response)) {
                log.info("共建点赞成功: contributionId={}, userId={}, likeCount={}", 
                        contributionId, userId, response.getData());
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("共建点赞失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "点赞失败");
        }
    }

    /**
     * 取消共建点赞
     *
     * @param contributionId 共建ID
     * @return 取消点赞结果
     */
    @PostMapping("/unlike/{contributionId}")
    public PAIResponseBean<Long> unlikeContribution(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            
            // 构建取消点赞请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 调用互动服务取消点赞
            PAIResponseBean<Long> response = resourceBehaviorClient.cancelBehavior(request);
            
            if (PAIResponseBeanUtil.isOk(response)) {
                log.info("取消共建点赞成功: contributionId={}, userId={}, likeCount={}", 
                        contributionId, userId, response.getData());
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("取消共建点赞失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "取消点赞失败");
        }
    }

    /**
     * 获取共建点赞状态
     *
     * @param contributionId 共建ID
     * @return 是否已点赞
     */
    @GetMapping("/like/status/{contributionId}")
    public PAIResponseBean<Boolean> getLikeStatus(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            
            // 构建查询请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 查询点赞状态
            return resourceBehaviorClient.isBehavior(request);
            
        } catch (Exception e) {
            log.error("获取共建点赞状态失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "获取点赞状态失败");
        }
    }

    /**
     * 获取共建点赞数量
     *
     * @param contributionId 共建ID
     * @return 点赞数量
     */
    @GetMapping("/like/count/{contributionId}")
    public PAIResponseBean<Long> getLikeCount(@PathVariable Long contributionId) {
        try {
            // 构建查询请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 查询点赞数量
            return resourceBehaviorClient.countBehavior(request);
            
        } catch (Exception e) {
            log.error("获取共建点赞数量失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "获取点赞数量失败");
        }
    }

    /**
     * 共建收藏
     *
     * @param contributionId 共建ID
     * @return 收藏结果
     */
    @PostMapping("/collect/{contributionId}")
    public PAIResponseBean<Long> collectContribution(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            
            // 构建收藏请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.COLLECT.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 调用互动服务进行收藏
            PAIResponseBean<Long> response = resourceBehaviorClient.behavior(request);
            
            if (PAIResponseBeanUtil.isOk(response)) {
                log.info("共建收藏成功: contributionId={}, userId={}", contributionId, userId);
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("共建收藏失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "收藏失败");
        }
    }

    /**
     * 取消共建收藏
     *
     * @param contributionId 共建ID
     * @return 取消收藏结果
     */
    @PostMapping("/uncollect/{contributionId}")
    public PAIResponseBean<Long> uncollectContribution(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            
            // 构建取消收藏请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.COLLECT.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);
            
            // 调用互动服务取消收藏
            PAIResponseBean<Long> response = resourceBehaviorClient.cancelBehavior(request);
            
            if (PAIResponseBeanUtil.isOk(response)) {
                log.info("取消共建收藏成功: contributionId={}, userId={}", contributionId, userId);
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("取消共建收藏失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "取消收藏失败");
        }
    }

    /**
     * 获取共建收藏状态
     *
     * @param contributionId 共建ID
     * @return 是否已收藏
     */
    @GetMapping("/collect/status/{contributionId}")
    public PAIResponseBean<Boolean> getCollectStatus(@PathVariable Long contributionId) {
        try {
            String userId = SessionHelper.getCurrentUserId();

            // 构建查询请求
            ResourceBehaviorRequestVO request = new ResourceBehaviorRequestVO();
            request.setUserId(userId);
            request.setBehaviorType(ResourceBehaviorConstants.BehaviorType.COLLECT.name());
            request.setResourceType("CONTRIBUTION");
            request.setResourceId(contributionId);

            // 查询收藏状态
            return resourceBehaviorClient.isBehavior(request);

        } catch (Exception e) {
            log.error("获取共建收藏状态失败: contributionId={}", contributionId, e);
            return PAIResponseBeanUtil.error(500, "获取收藏状态失败");
        }
    }

    /**
     * 批量获取共建交互数据
     *
     * @param contributionIds 共建ID列表，逗号分隔
     * @return 交互数据映射
     */
    @GetMapping("/batch")
    public PAIResponseBean<Map<String, Object>> getBatchInteractionData(@RequestParam String contributionIds) {
        try {
            String userId = SessionHelper.getCurrentUserId();
            String[] ids = contributionIds.split(",");
            Map<String, Object> result = new HashMap<>();

            for (String idStr : ids) {
                try {
                    Long contributionId = Long.parseLong(idStr.trim());
                    Map<String, Object> itemData = new HashMap<>();

                    // 获取点赞状态和数量
                    ResourceBehaviorRequestVO likeStatusRequest = new ResourceBehaviorRequestVO();
                    likeStatusRequest.setUserId(userId);
                    likeStatusRequest.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
                    likeStatusRequest.setResourceType("CONTRIBUTION");
                    likeStatusRequest.setResourceId(contributionId);

                    ResourceBehaviorRequestVO likeCountRequest = new ResourceBehaviorRequestVO();
                    likeCountRequest.setBehaviorType(ResourceBehaviorConstants.BehaviorType.LIKE.name());
                    likeCountRequest.setResourceType("CONTRIBUTION");
                    likeCountRequest.setResourceId(contributionId);

                    // 获取收藏状态
                    ResourceBehaviorRequestVO collectStatusRequest = new ResourceBehaviorRequestVO();
                    collectStatusRequest.setUserId(userId);
                    collectStatusRequest.setBehaviorType(ResourceBehaviorConstants.BehaviorType.COLLECT.name());
                    collectStatusRequest.setResourceType("CONTRIBUTION");
                    collectStatusRequest.setResourceId(contributionId);

                    try {
                        PAIResponseBean<Boolean> likeStatusResponse = resourceBehaviorClient.isBehavior(likeStatusRequest);
                        PAIResponseBean<Long> likeCountResponse = resourceBehaviorClient.countBehavior(likeCountRequest);
                        PAIResponseBean<Boolean> collectStatusResponse = resourceBehaviorClient.isBehavior(collectStatusRequest);

                        itemData.put("isLiked", likeStatusResponse.getData() != null ? likeStatusResponse.getData() : false);
                        itemData.put("likeCount", likeCountResponse.getData() != null ? likeCountResponse.getData() : 0L);
                        itemData.put("isCollected", collectStatusResponse.getData() != null ? collectStatusResponse.getData() : false);

                    } catch (Exception e) {
                        log.warn("获取共建交互数据失败: contributionId={}", contributionId, e);
                        itemData.put("isLiked", false);
                        itemData.put("likeCount", 0L);
                        itemData.put("isCollected", false);
                    }

                    result.put(contributionId.toString(), itemData);

                } catch (NumberFormatException e) {
                    log.warn("无效的共建ID: {}", idStr);
                }
            }

            return PAIResponseBeanUtil.success(result);

        } catch (Exception e) {
            log.error("批量获取共建交互数据失败: contributionIds={}", contributionIds, e);
            return PAIResponseBeanUtil.error(500, "获取交互数据失败");
        }
    }
}
